package com.mavenq.workflow.business.controller;


import org.camunda.bpm.engine.*;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.camunda.bpm.engine.history.HistoricTaskInstance;
import org.camunda.bpm.engine.repository.Deployment;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.engine.variable.VariableMap;
import org.camunda.bpm.engine.variable.Variables;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/flow")
public class FlowController {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private IdentityService identityService;
    @Autowired
    private HistoryService historyService;

    @GetMapping("/deploy")
    public String deploy(){
        Deployment deploy = repositoryService.createDeployment()
                .name("再部署第二个同样流程") // 定义部署文件的名称
                .tenantId("a")
                .source("http://localhost")
                .addClasspathResource("bpmn/shopingProcess.bpmn") // 绑定需要部署的流程文件
                .deploy();// 部署流程
        return deploy.getId() + ":" + deploy.getName();
    }


    /**
     * 启动流程的案例
     */
    @RequestMapping(value = "/startFlow", method = RequestMethod.GET)
    public void startFlow(String processDefinitionId){
        // 部署流程
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinitionId);
        // 部署的流程实例的相关信息
        System.out.println("processInstance.getId() = " + processInstance.getId());
        System.out.println("processInstance.getProcessDefinitionId() = " + processInstance.getProcessDefinitionId());
    }

    /**
     * 启动流程的案例
     */
    @RequestMapping(value = "/start/{processKey}", method = RequestMethod.GET)
    public void startProcessByKey(@PathVariable(value = "processKey") String processKey){
        identityService.setAuthenticatedUserId("admin");
        // 定义变量
        VariableMap variableMap = Variables.createVariables();
        variableMap.put("var", processKey);
        // 部署流程
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processKey, variableMap);
        // 部署的流程实例的相关信息
        System.out.println("processInstance.getId() = " + processInstance.getId());
        System.out.println("processInstance.getProcessDefinitionId() = " + processInstance.getProcessDefinitionId());
    }


    /**
     * 查询任务
     *    待办
     *
     *  流程定义ID:processDefinition : 我们部署流程的时候会，每一个流程都会产生一个流程定义ID
     *  流程实例ID:processInstance ：我们启动流程实例的时候，会产生一个流程实例ID
     */
    @RequestMapping(value = "/queryTask", method = RequestMethod.GET)
    public String queryTask(){
        List<Task> list = taskService.createTaskQuery()
                //.processInstanceId("eff78817-2e58-11ed-aa3f-c03c59ad2248")
//                .taskAssignee("demo")
                .list();

        if(list != null && list.size() > 0){
            for (Task task : list) {
                System.out.println("task.getId() = " + task.getId());
                System.out.println("task.getAssignee() = " + task.getAssignee());
            }
        }
        return "success queryTask";
    }

    /**
     * 查看历史流程实例的信息
     */
    @GetMapping("/queryHistoryProcInst")
    public String queryHistoryProcInst() {
        List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().list();
        if (CollectionUtils.isEmpty(list)) {
            return "Empty";
        }
        StringBuilder builder = new StringBuilder();
        for (HistoricProcessInstance instance : list) {
            builder.append("\n\n历史流程实例id").append(instance.getId())
                    .append("\n历史流程定义的id").append(instance.getProcessDefinitionId())
                    .append("\n历史流程实例开始时间--结束时间").append(instance.getStartTime()).append("-->").append(instance.getEndTime());
        }
        System.out.println(builder.toString());
        return builder.toString();
    }


    /**
     * 查询历史实例执行任务信息
     */
    @GetMapping("/queryHistoryTask")
    public String queryHistoryTask(String processInstanceId) {
        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).list();
        if (CollectionUtils.isEmpty(list)) {
            return "Empty";
        }
        StringBuilder builder = new StringBuilder();

        for (HistoricTaskInstance taskInstance : list) {
            builder.append("\n\n历史流程实例任务id:").append(taskInstance.getId());
            builder.append("\n历史流程定义的id:").append(taskInstance.getProcessDefinitionId());
            builder.append("\n历史流程实例任务名称:").append(taskInstance.getName());
            builder.append("\n历史流程实例任务处理人:").append(taskInstance.getAssignee());
        }
        String result = builder.toString();
        System.out.println(result);
        return result;
    }

}
